package org.cogaen.java2d.xml;

import java.awt.Image;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.cogaen.core.Core;
import org.cogaen.java2d.ImageUtil;
import org.cogaen.java2d.SpriteVisual;
import org.cogaen.logging.LoggingService;
import org.cogaen.resource.ResourceManager;

public class SpriteXmlHandle extends XmlHandle {

	private static final String LOGGING_SOURCE = ResourceManager.LOGGING_SOURCE;
	private SpriteParser spriteParser;
	
	public SpriteXmlHandle(String resourceName, String filename) {
		super(resourceName, filename, SpriteParser.createFilter(resourceName));
		this.spriteParser = new SpriteParser();
	}

	@Override
	protected Object parseXml(Core core, XMLStreamReader parser) throws XMLStreamException {
		try {
			this.spriteParser.parse(parser);
			return createSpriteVisual(core);
		} catch (ParseException e) {
			LoggingService logger = LoggingService.getInstance(core);
			logger.logWarning(LOGGING_SOURCE, "unable to load sprite visual '" + getName() + "': " + e.getMessage());
			return new SpriteVisual(ImageUtil.createDummyImage(core), 1.0, 1.0);
		}		
	}

	private Object createSpriteVisual(Core core) {
		Image image;
		if (this.spriteParser.getImageName() != null) {
			ResourceManager resMngr = ResourceManager.getInstance(core);
			if (resMngr.hasResource(this.spriteParser.getImageName())) {
				image = (Image) resMngr.getResource(spriteParser.getImageName());
			} else {
				LoggingService logger = LoggingService.getInstance(core);
				logger.logWarning(LOGGING_SOURCE, "referenced resource '" + spriteParser.getImageName() + "' not found");
				image = ImageUtil.createDummyImage(core);
			}
		} else {
			LoggingService logger = LoggingService.getInstance(core);
			logger.logWarning(LOGGING_SOURCE, "no image specified for sprite visual '" + getName() + "'");
			image = ImageUtil.createDummyImage(core);
		}
		
		double width = this.spriteParser.getWidth();
		double height = this.spriteParser.getHeight();
		
		if (width <= 0) {
			width = image.getWidth(null);
		}
		
		if (height <= 0) {
			height = image.getHeight(null);
		}
		
		SpriteVisual spriteVisual = new SpriteVisual(image, width, height);
		
		return spriteVisual;
	}

}
